import { UPLOADS_DIR } from "$lib/utils/paths";
import fs from "fs";
import path from "path";

const MIME_TYPES = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml", ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".pdf": "application/pdf" };

function isSafeFilename(name) {
  if (!name) return false;
  if (name.includes("\0")) return false;
  if (name.includes("..") || name.includes("/") || name.includes("\\")) return false;
  return true;
}

export async function GET({ params }) {
  const { filename } = params;
  if (!isSafeFilename(filename)) { return new Response("Invalid filename", { status: 400 }); }
  const filePath = path.join(UPLOADS_DIR, filename);
  const resolved = path.resolve(filePath);
  const uploadsResolved = path.resolve(UPLOADS_DIR);
  if (!resolved.startsWith(uploadsResolved + path.sep) && resolved !== uploadsResolved) { return new Response("Forbidden", { status: 403 }); }
  if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) { return new Response("File not found", { status: 404 }); }
  const ext = path.extname(resolved).toLowerCase();
  const mimeType = MIME_TYPES[ext] || "application/octet-stream";
  const stat = fs.statSync(resolved);
  const fileStream = fs.createReadStream(resolved);
  const encodedFilename = encodeURIComponent(path.basename(resolved));
  return new Response(fileStream, { status: 200, headers: { "Content-Type": mimeType, "Content-Length": String(stat.size), "Content-Disposition": `inline; filename="${path.basename(resolved)}"; filename*=UTF-8''${encodedFilename}` } });
}
